package slowtask

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"time"
	"cloud_worm/util/third/unotify"
	"cloud_worm/util/umodels/mysqldb/dbmanager"
)

// AgentOffline Agent下线事件相关
type AgentOffline struct {
	AgentId 		string
	AgentIP 		string
	Version 		int
	EventType 		int
}

// Done 执行
func (w *AgentOffline) Doing()  {
	// milan查询机器状态
	// todo: 查询机器状态

	var offlineMsg string

	// 接tt推送
	msg := fmt.Sprintf("| %d | %s | OFFLINE | %s |", w.Version, w.AgentIP, offlineMsg)
	logs.Notice(msg)

	ttItem := &unotify.IMNotifyItem {
		Grade:       unotify.WarnGrade,
		Title:       unotify.DefaultTitle,
		Msg:         msg,
		IMUsers:     []string{"用学"},
	}
	unotify.IMNotifyInst.SendAsync(ttItem)
	return
}

// UpdateAgentOfflineStatus 更新agent的status为offline
type UpdateAgentOfflineStatus struct {
	AgentId 	string
}

func (u *UpdateAgentOfflineStatus) Doing()  {
	wormId := dbmanager.WormId{
		AgentId: u.AgentId,
	}
	if err := wormId.Read("agent_id"); err != nil {
		logs.Error(fmt.Sprintf("read for `%s` error: %s", u.AgentId, err.Error()))
		return
	}
	if wormId.Status != dbmanager.AgentOffline {
		wormId.Status = dbmanager.AgentOffline
		wormId.Updated = time.Now().Unix()
		err := wormId.Update("status", "updated")
		if err != nil {
			logs.Error(fmt.Sprintf("updated for `%s` error: %s", u.AgentId, err.Error()))
			return
		}
	}

	return
}